#include "game.h"

Game::Game()
{
	cleargrid();
}

void Game::cleargrid()
{
	int i,j;
	for(i = 0; i < 3; i++)
		for(j = 0; j < 3; j++)
			grid[i][j] = 0;
}

void Game::printgrid()
{
	int i,j;
	for(i = 0; i < 3; i++)
	{
		cout << "\n";
		for(j = 0; j < 3; j++)
			cout << grid[i][j];
	}
}

void Game::set1(int x, int y)
{
	if(x < 0 || x > 2 || y < 0 || y > 2)
		cout << "Cannot set1 " << x << ", " << y << endl;
	else
		grid[x][y] = 1;
}

void Game::set2(int x, int y)
{
	if(x < 0 || x > 2 || y < 0 || y > 2)
		cout << "cannot set2 " << x << ", " << y << endl;
	else
		grid[x][y] = 2;
}

/*
Check for gameover conditions.  Returns 0 if not finished, 1 for player 1 winning, 
2 for player 2 winning, and 3 for game over with no winner.
*/
int Game::gameover()
{
	int c1, c2, tc, i, j;
	tc = 0;
	/*check for horizontal win*/
	for(i = 0; i < 3; i++)
	{
		c1 = 0;
		c2 = 0;
		for(j = 0; j < 3; j++)
		{
			if(grid[i][j] == 1)
			{
				c1++;
				tc++;
			}
			if(grid[i][j] == 2)
			{
				c2++;
				tc++;
			}
			if(c1 == 3)
				return 1;
			if(c2 == 3)
				return 2;
		}
	}
	if(tc == 9)
		return 3;

	/*check for vertical win*/
	for(i = 0; i < 3; i++)
	{
		c1 = 0;
		c2 = 0;
		for(j = 0; j < 3; j++)
		{
			if(grid[j][i] == 1)
				c1++;
			if(grid[j][i] == 2)
				c2++;
			if(c1 == 3)
				return 1;
			if(c2 == 3)
				return 2;
		}
	}

	/*check for diagonal '/' win*/
	if(grid[0][0] == 1 && grid[1][1] == 1 && grid[2][2] == 1)
		return 1;
	if(grid[0][0] == 2 && grid[1][1] == 2 && grid[2][2] == 2)
		return 2;

	/*check for diagonal '\' win*/
	if(grid[2][0] == 1 && grid[1][1] == 1 && grid [0][2] == 1)
		return 1;
	if(grid[2][0] == 2 && grid[1][1] == 2 && grid [0][2] == 2)
		return 2;

	/*game is not over*/
	return 0;
}

int main()
{
	Game gamegrid;
	gamegrid.set2(0,0);
	gamegrid.set2(1,0);
	gamegrid.set2(2,0);
	gamegrid.printgrid();
	cout << "\n\nWinner: " << gamegrid.gameover() << endl;
}
